<?php

class Ext_Article_Attachment_Image
{
    protected $_articleId;
    
    public function __construct($articleId)
    {
        if(!$articleId){
            require_once 'Ext/Article/Exception.php';
            throw new Ext_Article_Exception("Article id empty.");
        }
        
        $this->_articleId = $articleId;
    }
    
    public function add($ImageDataId)
    {
        $_articleImageRow = App_Model_DbTable_Article_Attachment_Image::getInstance()->getRowByArticleId($this->_articleId);
        if(!$_articleImageRow){
            $row = array(
                'articleId'     => $this->_articleId,
                'ids'           => $ImageDataId,
            );
            App_Model_DbTable_Article_Attachment_Image::getInstance()->addNew($row);
            
        }else{
            $_ids = $_articleImageRow['ids'];
            $_ids .= ';'.$ImageDataId;
            
            $row = array(
                'ids'     => $_ids,
            );
            App_Model_DbTable_Article_Attachment_Image::getInstance()->addOld($row, $this->_articleId);
        }
    }
    
    public function del($imageDataId)
    {
        $_articleImageRow = App_Model_DbTable_Article_Attachment_Image::getInstance()->getRowByArticleId($this->_articleId);
        if(!$_articleImageRow){
            return "";
        }
        
        $_ids = $_articleImageRow['ids'];
        
        $_newIdsArray = array();
        $_idsArray = explode(';', $_ids);
        for($i=0;$i<count($_idsArray);$i++)
        {
            $_id = $_idsArray[$i];
            if($_id == $imageDataId){
                continue;
            }
            
            if(in_array($_id, $_newIdsArray)){
                continue;
            }
            
            $_newIdsArray[] = $_id; 
        }
        
        $row = array(
            'ids'     => join(';', $_newIdsArray),
        );

        App_Model_DbTable_Article_Attachment_Image::getInstance()->addOld($row, $this->_articleId);
    }
}
